package com.android.duininsuoai.fragment.group;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.duininsuoai.activity.MainTab;
import com.android.duininsuoai.model.group.MainHeadNestSortData;
import com.android.duininsuoai.model.group.MainList;
import com.android.duininsuoai.model.group.MainListCallback;
import com.android.duininsuoai.model.group.MainSearchSortData;
import com.android.duininsuoai.utils.HttpUtils;
import com.android.duininsuoai.utils.ObjectUtils;
import com.android.duininsuoai.view.MyGridView;
import com.android.duininsuoai.view.recycleview.CustomLoadMoreView;
import com.android.duininsuoai.view.recycleview.CustomRecycleView;
import com.android.duininsuoai.adapt.MainlistAdapt;
import com.android.duininsuoai.utils.ConstantsUrl;
import com.android.duininsuoai.R;
import com.android.duininsuoai.fragment.BaseLazyFragment;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 分类商品列表页
 * ---------------------------------------
 */
public class Fragment_TabSearchList extends BaseLazyFragment implements BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R.id.main_top_bg)
    Toolbar mainTopBg;
    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;
    private View rootView;
    private MainlistAdapt adapter;
    private LayoutInflater inflater;
    private boolean networkConnected;
    private FragmentActivity mcontext;
    private static final String ARG_PARAM1 = "param1";
    private int mParam1;
    private static final String ARG_PARAM2 = "param2";
    private static final String ARG_PARAM3 = "param3";
    private List<MainSearchSortData.DataBean> mParam3;
    private String mParam2;
    private int page = 1;
    private View inflate;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getInt(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
            mParam3 = (List<MainSearchSortData.DataBean>) getArguments().getSerializable(ARG_PARAM3);
        }
    }

    public static Fragment_TabSearchList newInstance(int param1, String id, List<MainSearchSortData.DataBean> mListSort) {
        Fragment_TabSearchList fragment = new Fragment_TabSearchList();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, id);
        args.putSerializable(ARG_PARAM3, (Serializable) mListSort);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected void initPrepare() {
        ReFreshData();
    }

    private LinearLayoutManager mLayoutManager;
    private GridLayoutManager mGridLayoutManager;

    private void initRecycle() {
        adapter = new MainlistAdapt(mcontext, null, "0");
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);

        mLayoutManager = new LinearLayoutManager(mcontext);
        mGridLayoutManager = new GridLayoutManager(mcontext, 2);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.GetToTop((ImageView) rootView.findViewById(R.id.top), 0);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
                switch (view.getId()) {
                    case R.id.main_list_item_go_kai:
                        ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
                        break;
                }
                return false;
            }
        });
    }


    @Override
    protected void onInvisible() {

    }


    @Override
    protected void initData() {


        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        if (networkConnected) {
            GetListData(page, "&id=" + mParam2);
        } else {

            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }

    }


    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        rootView = inflater.inflate(R.layout.layout_recycle_refresh, container, false);
        ButterKnife.bind(this, rootView);
        mcontext = getActivity();
        mainTopBg.setVisibility(View.GONE);
        initRecycle();
        initHeadSort(mParam3);
        return rootView;
    }

    List<MainHeadNestSortData> mList_HeadSort = new ArrayList<>();

    private void initHeadSort(final List<MainSearchSortData.DataBean> tj_list) {
        if (tj_list == null || tj_list.size() == 0) {
            return;
        }
        List<MainSearchSortData.DataBean.SubBeanX> sub = tj_list.get(mParam1).getSub();
        if (sub == null || sub.size() == 0) {
            return;
        }
        if (sub.size() >= 8) {
            for (int i = 0; i < sub.size(); i++) {
                mList_HeadSort.add(new MainHeadNestSortData(sub.get(i).getId(), sub.get(i).getCatname(), sub.get(i).getThumb(), 0, sub.get(i).getParentid()));
                if (i == 6) {
                    break;
                }
            }
            mList_HeadSort.add(new MainHeadNestSortData("", "查看全部", null, R.mipmap.main_sort_all, tj_list.get(mParam1).getId()));
        } else {
            for (int i = 0; i < sub.size(); i++) {
                mList_HeadSort.add(new MainHeadNestSortData(sub.get(i).getId(), sub.get(i).getCatname(), sub.get(i).getThumb(), 0, sub.get(i).getParentid()));
            }
        }

        inflate = inflater.inflate(R.layout.head_search_sort_list_p, null, false);
        MyGridView nestlist_p = (MyGridView) inflate.findViewById(R.id.head_search_sort_list_nestlist_p);
        Adapt adapt = new Adapt(mList_HeadSort);
        nestlist_p.setAdapter(adapt);

        adapter.addHeaderView(inflate);

    }


    private void ReFreshData() {
        mRefreshLayout.setColorSchemeResources(R.color.app_title);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                networkConnected = ObjectUtils.isNetworkConnected(getActivity());
                if (networkConnected) {
                    page = 1;
                    GetListData(page, "&id=" + mParam2);
                } else {
                    ObjectUtils.toast(getActivity(), "网络连接出现异常");
                    mRefreshLayout.setRefreshing(false);
                }
            }
        });
    }

    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                page = 1;
                GetListData(page, "&id=" + mParam2);
                break;

        }
    }


    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetListData(page, "&id=" + mParam2);
    }

    private void GetListData(final int page, String type) {
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        String address = ConstantsUrl.domain + ConstantsUrl.MAIN_LISTDATA + "?page=" + page + type;
        Log.e("address", address);
        if (networkConnected) {
            HttpUtils.get(address, null, new MainListCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(MainList response, int id) {
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);

                    if (response.getCode() == 0) {

                        List<MainList.MainListdata.Mainlistdata> list = response.getData().getList();
                        if (list == null && page == 1) {
                            noData.setVisibility(View.VISIBLE);
                            return;
                        }
                        ArrayList<MainList.MainListdata.Mainlistdata> listdata = new ArrayList<>();

                        if (list != null && list.size() > 0) {
                            for (int i = 0; i < list.size(); i++) {
                                listdata.add(new MainList.MainListdata.Mainlistdata(response.getData().getList_type(), list.get(i).getId()
                                        , list.get(i).getTypeid(), list.get(i).getName(), list.get(i).getPrice(), list.get(i).getTeam_price(), list.get(i).getDiscount_price()
                                        , list.get(i).getThumb(), list.get(i).getTeam_num(), list.get(i).getTeam_people_num(), list.get(i).getLuck_num(), list.get(i).getEnd_time()
                                        , list.get(i).getStart_time(), list.get(i).getRun_time()));
                            }
                            if (page == 1) {
                                adapter.setNewData(listdata);
                                if (response.getData().getList_type() == 0) {
                                    mRecyclerView.setLayoutManager(mLayoutManager);
                                    mRecyclerView.setAdapter(adapter);
                                } else {
                                    mRecyclerView.setLayoutManager(mGridLayoutManager);
                                    mRecyclerView.setAdapter(adapter);
                                }
                            } else {
                                adapter.addData(listdata);
                                adapter.loadMoreComplete();
                            }
                        } else {
                            adapter.loadMoreEnd();
                        }
                    } else {
                        noData.setVisibility(View.VISIBLE);
                        noDataTv.setVisibility(View.VISIBLE);
                        noDataTv.setText(response.getMsg());
                    }
                }
            });
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(getActivity(), "网络连接出现异常");
            adapter.loadMoreFail();
        }
    }


    private class Adapt extends BaseAdapter {

        List<MainHeadNestSortData> listdata;

        public Adapt(List<MainHeadNestSortData> listdata) {
            this.listdata = listdata;
        }


        @Override
        public int getCount() {

            return listdata.size();


        }


        @Override
        public Object getItem(int position) {
            return null;
        }


        @Override
        public long getItemId(int position) {
            return 0;
        }


        @Override
        public View getView(final int pos, View convertView, ViewGroup parent) {
            View inflate_paystyle = LayoutInflater.from(mcontext).inflate(R.layout.list_pro_type_item, null);
            TextView typename = (TextView) inflate_paystyle.findViewById(R.id.typename);
            ImageView typeicon = (ImageView) inflate_paystyle.findViewById(R.id.typeicon);
            typename.setText(listdata.get(pos).getCatname());
            if (listdata.get(pos).getDrawable() == 0) {
                ObjectUtils.photo(mcontext, listdata.get(pos).getThumb(), typeicon);
            } else {
                typeicon.setImageResource(listdata.get(pos).getDrawable());
            }
            inflate_paystyle.findViewById(R.id.typell).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mcontext, MainTab.class);
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_TYPE, 2);
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_TYPE_SERACH, mList_HeadSort.get(pos).getParentid());
                    if (listdata.get(pos).getDrawable() == 0) {
                        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_ID, (pos + 1));
                    } else {
                        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_ID, 0);
                    }
                    startActivity(intent);
                }
            });
            return inflate_paystyle;
        }
    }
}
